package com.briup.corejava.chap12;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.Socket;

public class Test063_TcpClient {
    public static void main(String[] args) {
        // 创建Socket对象
        Socket socket = null;
        int port = 8888;
        String ip = "127.0.0.1";
        try {
            socket = new Socket(ip,port);
            // 看一下客户端的socket和服务器的socket是不是同一个
            System.out.println("客户端连接成功，正在发送数据...");
            String data = "账号：张三，密码：123，请求登陆";
            // 写入数据到socket中，肯定用输出流，这里算是一个节点流，主要和网络进行连接
            OutputStream out = socket.getOutputStream();
            out.write(data.getBytes());
            out.flush();
            socket.shutdownOutput();
            System.out.println("数据发送成功，等待服务器响应...");

            InputStream in = socket.getInputStream();
            int len = -1;
            byte[] buf = new byte[1024];
            System.out.println("客户端收到响应：");
            while ((len = in.read(buf)) != -1) {
                System.out.println(new String(buf, 0, len));
            }
            System.out.println("客户端请求结束，获得响应，流程完成！");

        } catch (IOException e) {
            throw new RuntimeException(e);
        } finally {
            if (socket != null) {
                try {
                    socket.close();
                } catch (IOException e) {
                    throw new RuntimeException(e);
                }
            }
        }
    }
}
